<?php
/**
 * Description: 抽奖
 * Author: hezhizheng
 * Date: 2018/5/11
 * Time: 14:18
 * Created by Created by Panxsoft.
 */

namespace App\Http\Controllers\MayPromo;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Promo\PromoCouponIndexRequest;
use App\Http\Requests\Promo\PromoCouponStoreRequest;
use App\Http\Requests\Promo\PromoCouponUpdateRequest;
use App\Models\MayPromoCoupon\MayPromoCoupon;
use App\Models\OpenWechat\WechatUser;
use App\Services\Utils\TimeHelper;
use Carbon\Carbon;

class PromoCouponController extends ApiController
{
    const LOTTERY_TIME = 3;

    const DISCOUNT_ZERO = 0;

    protected $coupons = [
        500, 300, 200, self::DISCOUNT_ZERO,
    ];
    
    /**
     * 购物券列表
     *
     * @param PromoCouponIndexRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \App\Exceptions\ApiException
     */
    public function index(PromoCouponIndexRequest $request)
    {
        /** @var WechatUser $wechat_user */
        $wechat_user = WechatUser::findByOpenId($request->openid);
            $this->checkItemExist($wechat_user, 'openid错误');

        $coupon_lists = $wechat_user->mayPromoCoupons()
            ->get();

        return $this->response(compact('coupon_count', 'coupon_lists'));
    }

    /**
     * @param PromoCouponStoreRequest $request
     *
     * @return array|\Illuminate\Http\Response
     * @throws \App\Exceptions\ApiException
     */
    public function store(PromoCouponStoreRequest $request) // 抽奖
    {
        /** 检测抽奖活动截止日期（2018-06-30） */
        $is_expired = Carbon::now()->lte('2018-06-30');
            $this->checkIsTrue($is_expired, '抽奖活动截止日期是：2018-06-30');

        /** @var WechatUser $wechat_user */
        $wechat_user = WechatUser::findByOpenId($request->openid);

        $this->lotteryDraw($wechat_user);

        $coupon_lists = $wechat_user->mayPromoCoupons()->get();

        $coupon_count = $coupon_lists->count();

        return $this->response(compact('coupon_count', 'coupon_lists'));
    }
    
    /**
     * @param PromoCouponUpdateRequest $request
     * @param                          $code
     *
     * @return array|\Illuminate\Http\Response
     * @internal param $id
     * @throws \App\Exceptions\ApiException
     */
    public function update(PromoCouponUpdateRequest $request, $code)  // 使用购物券
    {
        /** 检测优惠券的有效期（2018-06-30） */
        $is_expired = Carbon::now()->lte('2018-06-30');
            $this->checkIsTrue($is_expired, '优惠券截止使用日期是：2018-06-30');

        /** @var WechatUser $wechat_user */
        $wechat_user = WechatUser::findByOpenId($request->openid);
        $this->checkItemExist($wechat_user, 'openid错误');

        $coupon = $wechat_user->mayPromoCoupons()->where([
            ['code', $code],
            ['is_used', MayPromoCoupon::COUPON_NOT_USED]
        ])->first();

        $this->checkItemExist($coupon, '购物券');

        $used = $coupon->update([
            'is_used' => MayPromoCoupon::COUPON_USED
        ]);

        return $this->response(compact('used'));


    }

    /**
     * 处理抽奖
     *
     * @param WechatUser $wechat_user
     *
     * @throws \App\Exceptions\ApiException
     */
    private function lotteryDraw(WechatUser $wechat_user): void
    {
        // 检查是否已经抽了奖
        $this->checkUnless($wechat_user->mayPromoCoupons()->exists(), '只能参与一次抽奖');

        // 抽奖并过滤掉折扣是 0 的结果
        $coupons = array_filter(array_random($this->coupons, self::LOTTERY_TIME));

        $inserts = [];
        $now = now();
        foreach ($coupons as $discount) {
            $inserts []= [
                'code'           => TimeHelper::microTimeSerial(),
                'wechat_user_id' => $wechat_user->getKey(),
                'title'          => $discount . '元魔妆镜购物券',
                'desc'           => $discount . '元魔妆镜购物券',
                'discount'       => $discount,
                'created_at'     => $now,
                'updated_at'     => $now,
            ];
        }

        (new MayPromoCoupon)->insert($inserts);

        return;
    }
}